package com.cmcc.linlaker;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.cmcc.linlaker.bean.LoginBean;
import com.cmcc.linlaker.bean.UpdateBean;
import com.cmcc.linlaker.http.ApiDefine;
import com.cmcc.linlaker.http.ConfigManager;
import com.cmcc.linlaker.ui.mine.bean.UserBean;
import com.cmcc.linlaker.utils.BarUtils;
import com.cmcc.linlaker.utils.SPHelper;
import com.cmcc.linlaker.utils.ToastUtils;
import com.cmcc.linlaker.utils.UpdateManager;
import com.cmcc.linlaker.utils.Utils;
import com.cmcc.linlaker.view.UpdateDialog;
import com.cmcc.linlaker.volley.GsonRequestHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LoginActivity extends AppCompatActivity {
    private List<View> editList = new ArrayList<>();
    private boolean isRememberPwd = true;
    private boolean isLoginAuto = false;
    private ImageView cb_remember_pwd, cb_login_auto;
    private EditText edit_username, edit_password;
    private LinearLayout layout_login, layout_next;
    private TextView text_username_error, text_password_error;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        BarUtils.initStatusBar(this);
        BarUtils.setStatusBarTextColor(this, false);

        initView();
    }

    private void initView() {
        edit_username = findViewById(R.id.edit_username);
        edit_password = findViewById(R.id.edit_password);
        editList.add(edit_username);
        editList.add(edit_password);
        edit_password.setText(SPHelper.getPassword());
        edit_username.setText(SPHelper.getUsername());

        cb_remember_pwd = findViewById(R.id.cb_remember_pwd);
        cb_login_auto = findViewById(R.id.cb_login_auto);
        layout_login = findViewById(R.id.layout_login);
        layout_next = findViewById(R.id.layout_next);
        text_username_error = findViewById(R.id.text_username_error);
        text_password_error = findViewById(R.id.text_password_error);

        if (SPHelper.getAutoLogin()) {
            layout_login.setVisibility(View.GONE);
            layout_next.setVisibility(View.VISIBLE);
            layout_next.setFocusable(true);
            layout_next.setFocusableInTouchMode(true);
        } else {
            layout_login.setVisibility(View.VISIBLE);
            layout_next.setVisibility(View.GONE);
        }

        checkUpdate();
    }

    private UpdateBean updateBean;

    /**
     * 检测更新
     */
    private void checkUpdate() {
        GsonRequestHelper helper = new GsonRequestHelper(LoginActivity.this);
        helper.sendGETRequest(ConfigManager.updateUrl, UpdateBean.class, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    UpdateBean bean = (UpdateBean) data;
                    dealUpgrade(bean);
                }
            }
        });
    }


    private void dealUpgrade(final UpdateBean bean) {
        updateBean = bean;
        try {
            int versionCodeService = Integer.parseInt(bean.getVersion());
            PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
            int versionCodeLocal = pi.versionCode;

            if (versionCodeLocal < versionCodeService) {
                // 比服务器上的版本低 需要更新
                showUpdateDialog(bean);
            }

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }


    private void showUpdateDialog(UpdateBean bean) {
        final UpdateDialog dialog = new UpdateDialog(this, bean, R.style.CustomDialog);
        dialog.setNewVersionListener(new UpdateDialog.OnNewVersionListener() {
            @Override
            public void update() {
                dialog.dismiss();
                installApk();
            }
        });
        dialog.setOnDialogCancelListener(new UpdateDialog.OnDialogCancelListener() {
            @Override
            public void cancel() {
                dialog.dismiss();
            }
        });
        dialog.setCancelable(false);
        dialog.show();
    }

    /**
     * 下载apk  并获取安装权限
     */
    public void installApk() {
        UpdateManager updateManager = new UpdateManager(this, updateBean.getInstall_url());
        updateManager.showDownloadDialog();
    }


    @Override
    protected void onResume() {
        super.onResume();

        isOpenGpsService();
    }

    private void isOpenGpsService() {
        if (!Utils.isOPen(LoginActivity.this)) {
            openGpsNotice();
        } else {
            if (dialog != null) {
                dialog.dismiss();
            }
        }
    }

    private Dialog dialog;

    private void openGpsNotice() {
        AlertDialog.Builder builder = new AlertDialog.Builder(
                this);
        if (dialog == null) {
            dialog = builder.setTitle("提示")
                    .setMessage("GPS未打开，APP无法正常使用")
                    .setPositiveButton("去开启", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Utils.openGPS(LoginActivity.this);
                        }
                    }).create();
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        } else {
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }
    }

    /**
     * 记住密码选择
     */
    public void rememberPwdOption(View view) {
        if (isRememberPwd) {
            cb_remember_pwd.setImageResource(R.mipmap.login_cb_unchecked);
        } else {
            cb_remember_pwd.setImageResource(R.mipmap.login_cb_checked);
        }

        isRememberPwd = !isRememberPwd;
    }

    /**
     * 自动登录操作
     */
    public void loginAutoOption(View view) {
        if (isLoginAuto) {
            cb_login_auto.setImageResource(R.mipmap.login_cb_unchecked);
        } else {
            cb_login_auto.setImageResource(R.mipmap.login_cb_checked);
        }

        isLoginAuto = !isLoginAuto;
    }

    /**
     * 登录
     */
    public void login(View view) {
        String username = edit_username.getText().toString();
        String password = edit_password.getText().toString();

        if (TextUtils.isEmpty(username)) {
            text_username_error.setText("用户名不能为空");
            text_username_error.setVisibility(View.VISIBLE);
        } else if (TextUtils.isEmpty(password)) {
            text_username_error.setVisibility(View.GONE);

            text_password_error.setText("密码不能为空");
            text_password_error.setVisibility(View.VISIBLE);
        } else {
            text_username_error.setVisibility(View.GONE);
            text_password_error.setVisibility(View.GONE);

            doLogin(username, password);
        }
    }

    /**
     * 登录
     */
    private void doLogin(String username, String password) {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("username", username);
        params.put("password", password);
        params.put("channeId", SPHelper.getChannelId());
        if (isRememberPwd) {
            params.put("rememberMe", true + "");
        } else {
            params.put("rememberMe", false + "");
        }

        helper.sendPOSTRequest(ApiDefine.LOGIN, LoginBean.class, params, true, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    LoginBean bean = (LoginBean) data;

                    if (bean.code.equals("0")) {
                        text_username_error.setVisibility(View.GONE);
                        ToastUtils.showText(LoginActivity.this, "登录成功");
                        ConfigManager.loginData = bean.data;

                        layout_login.setVisibility(View.GONE);
                        layout_next.setVisibility(View.VISIBLE);
                        layout_next.setFocusable(true);
                        layout_next.setFocusableInTouchMode(true);

                        SPHelper.setAuthToken(bean.data.token);
                        SPHelper.setUid(bean.data.userId);
                        Utils.hideSoftKeyboard(LoginActivity.this, editList);
                        SPHelper.setUsername(edit_username.getText().toString());

                        getUserDetail();

                        if (isRememberPwd) {
                            SPHelper.setPassword(edit_password.getText().toString());
                        }

                        if (isLoginAuto) {
                            SPHelper.setAutoLogin(true);
                        } else {
                            SPHelper.setAutoLogin(false);
                        }
                    } else {
                        text_username_error.setVisibility(View.VISIBLE);
                        text_username_error.setText(bean.msg);
                    }
                }
            }
        });
    }

    /**
     * 用户详情
     */
    private void getUserDetail() {
        GsonRequestHelper helper = new GsonRequestHelper(LoginActivity.this);
        Map<String, String> params = new HashMap<>();
        String getUrl = ApiDefine.USER_INFO;
        helper.sendPOSTRequest(getUrl, UserBean.class, params, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    UserBean bean = (UserBean) data;
                    SPHelper.setUid(bean.userId);
                    SPHelper.setNickname(bean.userName);
                }
            }
        });
    }

    /**
     * 非接触性执法
     */
    public void next_function_law(View view) {
        if (!checkAppInstalled(this, "com.cci.cacg")) {
            ToastUtils.showText(this, "请先安装执法APP");
        } else {
            //admin sa
            String username = edit_username.getText().toString();
            String password = edit_password.getText().toString();

            Intent intent = getPackageManager().getLaunchIntentForPackage("com.cci.cacg");
            if (intent != null) {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("externalUsername", username);
                intent.putExtra("externalPassword", password);
                startActivity(intent);
            }
        }
    }

    /**
     * 临湖地带管控
     */
    public void next_function_manage(View view) {
        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(intent);

        finish();
    }

    private boolean checkAppInstalled(Context context, String pkgName) {
        if (pkgName == null || pkgName.isEmpty()) {
            return false;
        }
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(pkgName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        if (packageInfo == null) {
            return false;
        } else {
            return true;//true为安装了，false为未安装
        }
    }

}
